import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:yyshort/common/apis/apis.dart';
import 'package:yyshort/common/model/video_model.dart';
import 'package:yyshort/pages/personal/personal/controller.dart';

import 'index.dart';

class FavoriteListController extends GetxController {
  FavoriteListController();

  final state = FavoriteListState();

  /// UI 组件
  final RefreshController refreshController = RefreshController(
    initialRefresh: true,
  );

  // 搜索请求
  String searchStr = '';
  int curPage = 1;
  int total = 15;

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
    //更新用户信息
    final PersonalController temPonnalCTL = Get.find<PersonalController>();
    temPonnalCTL.onReady();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }

  void onRefresh() {
    fetchNewsList(isRefresh: true)
        .then((_) {
          refreshController.refreshCompleted(resetFooterState: true);
        })
        .catchError((_) {
          refreshController.refreshFailed();
        });
  }

  void onLoading() {
    fetchNewsList()
        .then((_) {
          if (state.videoList.length <= total * curPage) {
            refreshController.loadNoData();
          } else {
            refreshController.loadComplete();
          }
        })
        .catchError((_) {
          refreshController.loadFailed();
        });
  }

  Future<void> fetchNewsList({bool isRefresh = false}) async {
    if (isRefresh == true) {
      curPage = 1;
      // 调试：打印当前页码，确认请求参数正确
    } else {
      curPage++;
    }

    // 调试：打印当前页码，确认请求参数正确
    print("FavoriteListController-------请求页码: $curPage");
    List<VideoModel> result = await UserAPI.my_video_shelf(curPage);
    // 网络请求完成后，根据需要清空列表
    if (isRefresh == true) {
      state.videoList.clear(); // 移到这里，确保请求成功后再清空
    }
    state.videoList.addAll(result);
    if (isRefresh == true && state.videoList.isEmpty) {
      state.isNeedShowEmpty.value = true;
    } else {
      state.isNeedShowEmpty.value = false;
    }
  }
}
